﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using TIMSComponents.Choisers;
using System.Collections.Specialized;
namespace TIMSComponents
{
    [ToolboxItem(true)]
    public partial class Choiser : BaseControl 
    {
        public ResultManager ResultManager = new ResultManager();
        //Access, select and filter data 
        private DataAccessLayer DAL = new DataAccessLayer();        
        //datasource
        private DataTable DataSource;

        private FrmFindM FrmFindM1;
        //Choiser List form
        private ListContainer ListContainer1;

        private PopupWindowHelper PopUp = new PopupWindowHelper();

        //Choiser initialization
        public Choiser()
        {
            InitializeComponent();
            this.EnabledChanged += new EventHandler(Choiser_EnabledChanged);
            this.OnfieldListChanged += new fieldListDelegate(Choiser_OnfieldListChanged);
            this.OnsqlCommandTextChanged += new SqlCommandTextDelegate(Choiser_OnsqlCommandTextChanged);
            this.OnsqlParamsChanged += new SqlParamsDelegate(Choiser_OnsqlParamsChanged);
            this.OnreturnedField += new ReturnedFieldDelegate(Choiser_OnreturnedField);
            this.OnallowRefreshChanged += new AllowRefreshDelegate(Choiser_OnallowRefreshChanged);
            this.OnChoiserTypeChanged += new ChoiserTypeDelegate(Choiser_OnChoiserTypeChanged);
            this.OnIdentityValueChanged += new IdentityValueDelegate(Choiser_OnIdentityValueChanged);
            this.ConnectionStringChanged += new ConnectionStringDelegate(Choiser_ConnectionStringChanged);
        }

        void Choiser_ConnectionStringChanged(string Value)
        {
            globalC.ConnectionString = Value;
        }

        void Choiser_OnIdentityValueChanged(object Value)
        {
            if (Value == DBNull.Value)
            {
                Result.Clear();
                textBoxSearch1.Text = "";
                return;
            }
            if (ReturnedField != null)
            {
                DataTable dt = new DataTable();
                string SqlText;
                SqlText = CMain.GetSelectCommand(SQLcommandText, SQLcommandType, FieldList, SqlParams);
                SqlText = SqlText + "  where " + IdentityFild + "=" + Convert.ToInt16(IdentityValue).ToString();
                dt = DAL.GetDataFromSQL(CMain.BuildDataTableStructure(FieldList), SqlText);
                if (dt.Rows.Count != 1)
                {
                    return;
                }
                Result = new StringDictionary();
                int MinItem = Math.Min(ReturnedField.Length, dt.Columns.Count);
                for (int i = 0; i < MinItem; i++)
                {
                    Result.Add(ReturnedField[i], dt.Rows[0][ReturnedField[i]].ToString());                        
                }
                textBoxSearch1.Text = ResultManager.GetResult(Result, FieldKeyNS);
            }
            else
            {
                MessageBox.Show("ReturnedField's value is null", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



        [Category("(TIMS)Textbox Control")]
        public TextBox TextBoxSearch
        {
            get
            {
                return textBoxSearch1;
            }
            set
            {
                textBoxSearch1 = TextBoxSearch;
            }
        }

        #region ---------Property changed events------------


        void Choiser_EnabledChanged(object sender, EventArgs e)
        {
            if (this.Enabled)
            {
                textBoxSearch1.BackColor = Color.White;
            }
            else
            {
                textBoxSearch1.BackColor = Color.LightGray;
                
                
            }
        }

        //Faired when AllowRefresh propery was changed
        void Choiser_OnallowRefreshChanged(bool Refresh)
        {
            //datasource was filtered.
            //Need new data from Ms SQL, without whereCondition
            if (Refresh == false)
            {
                //if Ostatus is false, we'll get new data from MS SQL
                Ostatus = false;
            }
        }

        //Faired when FieldList propery was changed
        void Choiser_OnfieldListChanged(string[] fieldList)
        {
            Ostatus = false;
        }
 

        //Faired when sqlParams propery was changed
        void Choiser_OnsqlParamsChanged(string sqlParams)
        {
            Ostatus = false;
        }

        //Faired when returnedField propery was changed
        void Choiser_OnreturnedField(string[] returnedField)
        {
            Ostatus = false;
        }

        //Faired when sqlCommandText propery was changed
        void Choiser_OnsqlCommandTextChanged(string sqlCommandText)
        {
            Ostatus = false;
        }

        void Choiser_OnChoiserTypeChanged(ChoiserType ChoiserTypeA)
        {
            switch (ChoiserTypeA)
            {
                case ChoiserType.asChoiser:
                    textBoxSearch1.ReadOnly = true;
                    break;
                case ChoiserType.asChoiserList:
                    textBoxSearch1.ReadOnly = false;
                    break;
                case  ChoiserType.asTextBox:
                    textBoxSearch1.ReadOnly =false;
                    break;
            }
        }

        #endregion


        //show result on textbox
        private void ShowResult()
        {
            if (ReturnedField.Length == 2 && ReturnedField != null)
            {
                string ResultAsCode = ResultManager.GetResult(Result, ReturnedField[0]);
                string ResultAsTxt = ResultManager.GetResult(Result, ReturnedField[1]);
                if (ResultAsTxt != null && ResultAsCode!=null)
                {
                    textBoxSearch1.Text = ResultAsTxt;
                    textBoxSearch1.Tag = ResultAsCode;
                }
            }
            else
            {
                MessageBox.Show(this, "ReturnedField[0] or ReturnedField[1]  property value is NULL", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool CheckParameters()
        {
            if (string.IsNullOrEmpty(FieldKeyNN) || string.IsNullOrEmpty(FieldKeyNN))
            {
                MessageBox.Show(this, "FieldKeyNN or FieldKeyNS parameters are null , please check parameters", "Choiser", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            else if (ReturnedField == null)
            {
                MessageBox.Show(this, "ReturnedField parametr is null, please check parameter", "Choiser", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            else
            {
                return false;
            }
        }

        private bool GetDataProc()
        {
            //If object isn't formed or if need live data
            if (Ostatus == false || AllowRefresh)
            {
                //Get SQL text 
                string SqlText = CMain.GetSelectCommand(SQLcommandText, SQLcommandType, FieldList, SqlParams);

                if (SqlText == null)
                {
                    MessageBox.Show(this, "Can't build SQL select, please check parameters", "Choiser", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                else
                {
                    DataSource = DAL.GetDataFromSQL(CMain.BuildDataTableStructure(FieldList), SqlText);
                    if (DataSource != null)
                    {
                        Ostatus = true;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            else
            {
                return true;
            }
        }



        void ParentForm_Load(object sender, EventArgs e)
        {
          
            string SqlText;
            if (AutoStart && base.ChoiserType != ChoiserType.asTextBox)
            {
                //Get SQL text 
                SqlText = CMain.GetSelectCommand(SQLcommandText, SQLcommandType, FieldList, SqlParams);
                //If all parameters are OK!
                if (SqlText != null)
                {
                    if (Ostatus == false)
                    {
                        //Get data from Ms SQL data base and set DataSource
                        DataSource = DAL.GetDataFromSQL(CMain.BuildDataTableStructure(FieldList), SqlText);
                        if (DataSource != null)
                        {
                            Ostatus = true;
                        }
                    }
                }
                else
                {
                    MessageBox.Show(this, "Can't build SQL select, please check parameters", "Choiser", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void Choiser_Load(object sender, EventArgs e)
        {
            //If autostart is true, data will be selected before ParentForm has been loaled
            ParentForm.Load += new EventHandler(ParentForm_Load);
         
            
        }       

        private void textBoxSearch1_Leave(object sender, EventArgs e)
        {
            if (ListContainer1 != null)
            {
                ListContainer1.Close();
            }
        }

        private void textBoxSearch1_KeyDown(object sender, KeyEventArgs e)
        {

            if (ChoiserType == ChoiserType.asChoiserList)
            {
                if ((char.IsControl((char)e.KeyCode) == false && e.KeyCode != Keys.End && e.KeyCode != Keys.Home) || e.KeyCode == Keys.Down)
                {
                    if (ListContainer1 == null)
                    {
                        ShowListAsDeactivate();
                    }
                }

                if (ListContainer1 != null)
                {
                    ListContainer1.KeyDownEvent(e);

                }
            }
            else if (ChoiserType == ChoiserType.asChoiser && e.KeyData==Keys.Enter)
            {                
                this.ShowForm(textBoxSearch1.Text);
            }
        }


        private void textBoxSearch1_KeyPress(object sender, KeyPressEventArgs e)
        {
       
            if (char.IsControl(e.KeyChar))
            {
                e.Handled = false;
                return; 
            }

            if (ChoiserType == ChoiserType.asChoiser)
            {
                ShowForm(e.KeyChar.ToString());
            }  
            else if (ChoiserType == ChoiserType.asTextBox) { return; }
            else
            {
                return;
            }
            
        }

        private void textBoxSearch1_TextChanged(object sender, EventArgs e)
        {
            if(ChoiserType == ChoiserType.asChoiserList)
            {
                if (ListContainer1!=null)
                {
                    ListContainer1.OnExpressionTextChanged(textBoxSearch1.Text);
                }                
            }
        }


        #region Choiser FrmFindM
        //Load FrmFindM form and activate it as modal. 
        public bool ShowForm(string TypedTxtForSearch)
        {
            if (CheckParameters())
            {
                return false;
            }

            if (GetDataProc())
            {
                FrmFindM1 = new FrmFindM(DataSource, FieldKeyNN, FieldKeyNS, ReturnedField, SortFN, CollumsWidth, CollumsCapiton, TypedTxtForSearch);
                FrmFindM1.FormClosed += new FormClosedEventHandler(FrmFindM1_FormClosed);
                FrmFindM1.ShowDialog(this);
                return true;
            }
            else
            {
                return false;
            }
        }

        void FrmFindM1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Result = FrmFindM1.Result;
            ShowResult();
            FrmFindM1 = null;
        }
        #endregion

        #region ChoiserList methods

        protected override void OnHandleCreated(EventArgs e)
        {
            if (ParentForm == null)
            {
                return;
            }
            PopUp.AssignHandle(ParentForm.Handle);
            //PopUp.AssignHandle(ParentForm.Handle);          

        }

        public bool ShowListAsDeactivate()
        {
            if (CheckParameters())
            {
                return false;
            }

            if (GetDataProc())
            {
                ListContainer1 = new ListContainer(DataSource, FieldKeyNN, FieldKeyNS, SortFN, CollumsWidth,CollumsCapiton, ReturnedField);
                ListContainer1.FormClosed += new FormClosedEventHandler(ListContainer1_FormClosed);
                //set ListContainer1's width Choiser's width
                ListContainer1.Width = Width;
                Point location = this.PointToScreen(new Point(textBoxSearch1.Left, textBoxSearch1.Bottom));
                //show ListContainer1 form as PopUp
                PopUp.ShowPopup(ParentForm, ListContainer1, location);
                textBoxSearch1.Focus();
                textBoxSearch1.SelectionStart = textBoxSearch1.Text.Length;
                return true;
            }
            else
            {
                return false;
            }
        }


        void ListContainer1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Result = ListContainer1.Result;
            ShowResult();
            ListContainer1 = null;
        }

        #endregion


    }
}
